package me.flyray.bsin.server.utils;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import javax.json.JsonException;
import java.io.IOException;
import java.util.List;

public class JsonUtils {
    private static final ObjectMapper om = createObjectMapper();

    public static ObjectMapper createObjectMapper() {
        ObjectMapper om = new ObjectMapper();

        // 反序列化时，忽略Javabean中不存在的属性，而不是抛出异常
        om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        // 忽略入参没有任何属性导致的序列化报错
        om.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);

        return om;
    }

    public static <T> List<T> toListOfObject(String json, Class<T> clazz, ObjectMapper om) {
        try {
            @SuppressWarnings("unchecked") Class<T[]> arrayClass = (Class<T[]>) Class
                    .forName("[L" + clazz.getName() + ";");
            return Lists.newArrayList(om.readValue(json, arrayClass));
        } catch (IOException | ClassNotFoundException e) {
//            log.error("json={}, clazz={}", json, clazz, e);
            System.out.println("json=" + json + ", clazz=" + clazz + " " + e.toString());
            throw new JsonException(e.toString());
        }
    }

    public static String toJson(Object obj) {
        Gson gson = (new GsonBuilder()).setPrettyPrinting().disableHtmlEscaping().create();
        return gson.toJson(obj);
    }
}
